/*
 * saco.h
 *
 *      Author: Jesus Jerez
 *   Copyright: GPL3
 */

#ifndef SACO_H_
#define SACO_H_

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <unistd.h>
#include <sys/stat.h>

/* GUI file */
#define GLADE_FILE "sacoui.glade"

/* Functions */
char *glade_file();
char *exec_path();


/* locate glade file */
char *glade_file()
{
	char *exepath;
	struct stat file_info;
	int status = 1;

	exepath = exec_path();
	strcat(exepath, "/share/saco/data/"); // release dir
	strcat(exepath, GLADE_FILE);

	/* evaluate if file exist */
	if(stat(exepath, &file_info) == 0)
		status = 0;
	else
	{
		memset(exepath, '\0', PATH_MAX+1);
		exepath = exec_path();
		strcat(exepath, "/data/"); // devel (src) dir
		strcat(exepath, GLADE_FILE);

		/* evaluate if file exist */
		if(stat(exepath, &file_info) == 0)
			status = 0;
		else
			fprintf(stderr, "Could not read \"%s\" file\n", GLADE_FILE);
	}

	return exepath;
}

/* get path of executable */
char *exec_path()
{
	char *exepath;
	char fullpath[PATH_MAX+1];
	char cleanpath[PATH_MAX+1];
	int i, path_len;
	int cslash = 0;

	path_len = readlink("/proc/self/exe", fullpath, sizeof(fullpath));
	fullpath[path_len] = '\0';

	/* clean path to get the parent directory */
	for(i=path_len ; i>=0 ; i--)
	{
		if(fullpath[i] == '/')
		{
			cslash++;
			if(cslash == 2)
			{
				cslash = i;
				break;
			}
		}
	}

	exepath = cleanpath;
	memcpy(cleanpath, fullpath, cslash);
	return exepath;
}

#endif /* SACO_H_ */
